let express = require("express");
let router = express.Router();
let articleOnlineDraft = require("../model/articleOnlineDraft")
let resourceOnlineDraft = require("../model/resourceOnlineDraft")
let answerOnlineDraft = require("../model/answerOnlineDraft")

router.post("/api/v1/post_onlineArticleDraft", async function (req, res) {
  try {
    let articleId = req.body.articleId
    let draft = await articleOnlineDraft.find({
      articleId
    })
    if (draft.length == 0) {
      let doc = new articleOnlineDraft(req.body)
      let onlineDraft = await doc.save();
      res.json({
        code: 200,
        data: onlineDraft._id
      })
    } else {
      res.json({
        code: 200,
        data: draft[0]._id
      })
    }
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});

router.post("/api/v1/post_onlineResourceDraft", async function (req, res) {
  try {
    // console.log(req.body);
    let articleId = req.body.articleId
    let draft = await resourceOnlineDraft.find({
      articleId
    })
    if (draft.length == 0) {
      let doc = new resourceOnlineDraft(req.body)
      let onlineDraft = await doc.save();
      res.json({
        code: 200,
        data: onlineDraft._id
      })
    } else {
      res.json({
        code: 200,
        data: draft[0]._id
      })
    }
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});

router.post("/api/v1/post_onlineAnswerDraft", async function (req, res) {
  try {
    // console.log(req.body);
    let articleId = req.body.articleId
    let draft = await answerOnlineDraft.find({
      articleId
    })
    if (draft.length == 0) {
      let doc = new answerOnlineDraft(req.body)
      let onlineDraft = await doc.save();
      res.json({
        code: 200,
        data: onlineDraft._id
      })
    } else {
      res.json({
        code: 200,
        data: draft[0]._id
      })
    }
  } catch (error) {
    console.log(error);
    res.status(500).send(error);
  }
});

module.exports = router;